package com.sdonkey.score.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sdonkey.score.constants.RedisKey;
import com.sdonkey.score.dao.AdGiftDao;
import com.sdonkey.score.model.AdPlacementGiftListBean;
import com.sdonkey.score.model.FinishPlacementAdBean;
import com.sdonkey.score.service.AdPlaceGiftService;
import com.sdonkey.score.util.RedPackage;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static java.math.BigDecimal.ROUND_HALF_UP;

/**
 * Created by hujun on 2018\12\19 0019.
 */
@Service("adPlaceGiftService")
@Transactional
public class AdPlaceGiftServiceImpl implements AdPlaceGiftService {
    public Logger logger = LoggerFactory.getLogger(AdPlaceGiftServiceImpl.class);
    @Autowired
    AdGiftDao adGiftDao;
    @Autowired
    private JedisPool jedisPool;

    @Override
    public List<FinishPlacementAdBean> getUnGiftAdList(String advId) {
        return adGiftDao.getUnGiftPlacementAd(advId);
    }

    @Override
    public JSONObject getAdPlaceLimitById(int adId) {

        Map adGift = adGiftDao.getAdPlaceGiftByAdId(adId);
        if (adGift == null) {
            return null;
        }
        JSONObject result = JSONObject.parseObject(JSON.toJSONString(adGift));
        return result;
    }

    @Override
    public Integer setAdPlaceGift(JSONObject params) {
        Map<String, Object> itemMap = JSONObject.toJavaObject(params, Map.class);
        if (itemMap.containsKey("id")) {//修改
            adGiftDao.updatePlaceGiftById(itemMap);
        } else {//添加
            itemMap.put("status", 1);
            adGiftDao.addAdPlaceGift(itemMap);
        }
        //添加成功新增红包数据
        Integer id = (Integer) itemMap.get("id");
        Map giftDetail = adGiftDao.getAdPlaceGiftById(id);
        String adId = giftDetail.get("adId").toString();
        Map adGift = adGiftDao.getAdPlaceGiftByAdId(Integer.valueOf(adId));
        JSONObject result = JSONObject.parseObject(JSON.toJSONString(adGift));
        autoGenerateRedEnvelopes(result);
        return id;
    }

    @Override
    public List<AdPlacementGiftListBean> getAdPlaceGiftList(String advId) {
        if (StringUtils.isBlank(advId)) {
            return null;
        }
        List<AdPlacementGiftListBean> list = adGiftDao.getGiftPlacementAdList(advId);
        return list;
    }

    @Override
    public void deleteAdPlaceGift(int id) {
        Map giftDetail = adGiftDao.getAdPlaceGiftById(id);
        String adId = giftDetail.get("adId").toString();
        adGiftDao.deleteById(id);
        try {
            Jedis jedis = jedisPool.getResource();
            jedis.del(RedisKey.ad_gift_key + adId);
        }catch (Exception e){
            e.printStackTrace();
        }
    }



    private void autoGenerateRedEnvelopes(JSONObject result) {

        Jedis jedis = jedisPool.getResource();
        String adId = result.getString("adId");
        String deliveyPrice = result.getString("deliveyPrice");//投放单价
        String releaseAmount = result.getString("releaseAmount");//投放金额
        String placeBalance = result.getString("advertiserBalance");//剩余余额
        Integer giftRatio = result.getInteger("giftRatio");//投放红包占比
        String giftLowerLimit = result.getString("giftLowerLimit");//红包投放下限
        String giftUpperLimit = result.getString("giftUpperLimit");//红包投放上限
        if(StringUtils.isNotBlank(placeBalance)){
            releaseAmount = placeBalance;
        }

        int times = 0;//预估的红包投放次数
        if (StringUtils.isNotBlank(deliveyPrice) && StringUtils.isNotBlank(releaseAmount) && giftRatio != null && StringUtils.isNotBlank(giftLowerLimit) && StringUtils.isNotBlank(giftUpperLimit)) {
            logger.info("==========开始生成红包数据===adId : {}", adId);
            BigDecimal balance = new BigDecimal(releaseAmount);//金额
            BigDecimal price = new BigDecimal(deliveyPrice);//单价
            Float leftRatio = (float)(100 - giftRatio) / 100;
            BigDecimal giftBalance = balance.multiply(new BigDecimal(giftRatio)).divide(new BigDecimal(100),2, RoundingMode.HALF_UP);
            times = balance.multiply(new BigDecimal(leftRatio)).divide(price, ROUND_HALF_UP).intValue();
            RedPackage redPackage = new RedPackage(Float.valueOf(giftLowerLimit), Float.valueOf(giftUpperLimit));
            List<Float> redPackets = redPackage.splitRedPackets(giftBalance.floatValue(), times);
            logger.info("==========生成红包数量===size : {}", redPackets.size());
            List<String> values = new ArrayList<>();
            for(Float item: redPackets){
                values.add(item.toString());
            }
            Collections.shuffle(values);//将顺序打乱
            if(jedis.exists(RedisKey.ad_gift_key+adId)) {
                jedis.del(RedisKey.ad_gift_key + adId);
            }
            jedis.lpush(RedisKey.ad_gift_key + adId, values.toArray(new String[]{}));
            logger.info("==========更新redis红包数据完成");
        }



    }

}
